/*
 * DMFE - Dirty Mesh Front End
 *
 * A simple HTML5 browser app to let untrained users
 * communicate over an ad-hoc network,
 * possibly during an internet outage.
 *
 * Copyright 2013 Dean Hall.
 * See LICENSE.txt for details.
 */

window.onload = function()
{
  sjcl.random.startCollectors();

  // If identity is present
  if (identityIsPresent())
  {
    // Enable the Dash page and show it
    pageSelect = document.getElementById("PageSelect");
    pageSelect.innerHTML += '<option value="Dash">Dash</option>';
    pageSelect.selectedIndex = pageSelect.length - 1;
    showSection("Dash");

    // Update the header with the identity
    cert = JSON.parse(localStorage['Certificate']);
    updateHeaderId(cert['AssuredFields']['Identity']);
  }
}


function identityIsPresent()
{
    return localStorage['Certificate'] && localStorage['PrivateKey'];
}


function getSelected()
{
    pageSelect = document.getElementById("PageSelect");
    return pageSelect.value;
}


function showSection(sectionName)
{
    // Hide all but the named section
    allSections = ["Welcome", "Identity", "Dash"];
    for (i in allSections)
    {
        section = document.getElementById(allSections[i])
        section.hidden = (allSections[i] != sectionName);
    }

    if ((sectionName == "Identity") && (identityIsPresent()))
    {
        cert = JSON.parse(localStorage['Certificate']);
        identity = cert['AssuredFields']['Identity'];
        document.getElementById("IdentityFirstNameTextBox").value = identity['FirstName'];
        document.getElementById("IdentityLastNameTextBox").value = identity['LastName'];
        document.getElementById("IdentityEmailTextBox").value = identity['Email'];
        document.getElementById("IdentityCallsignTextBox").value = identity['Callsign'];
        cb = document.getElementById("LicensedRadioOperatorCheckBox");
        cb.checked = (identity['Callsign'] != "");
        // Click twice to active the checkbox's onchange macro
        cb.click();
        cb.click();
    }
}


function initMedia()
{
    window.URL = window.URL || window.webkitURL;
    navigator.getUserMedia = navigator.getUserMedia
        || navigator.webkitGetUserMedia
        || navigator.mozGetUserMedia
        || navigator.msGetUserMedia;
}


// FIXME
function takePhoto()
{
    canvas = document.getElementById("facePhotoCanvas");
    context = canvas.getContext("2d");
    context.drawImage(video, 0, 0, 256, 256);
}


function updateHeaderId( id )
{
    // Update the page header with identity
    headerId = document.getElementById("HeaderId");
    headerId.innerHTML = "Identity: " + id.FirstName + ' ' + id.LastName;
    if (id.Callsign != "")
    {
        headerId.innerHTML += " ( " + id.Callsign + " )";
    }
}


function generateIdentityCert()
{
    // Identity: {first, last, email [, callsign], publicKey}
    identity = {};
    identity.FirstName = document.getElementById("IdentityFirstNameTextBox").value.trim();
    identity.LastName = document.getElementById("IdentityLastNameTextBox").value.trim();
    identity.Email = document.getElementById("IdentityEmailTextBox").value.trim();
    identity.Callsign = (document.getElementById("LicensedRadioOperatorCheckBox").checked)
                      ? document.getElementById("IdentityCallsignTextBox").value.trim().toUpperCase()
                      : "";

    updateHeaderId(identity);

    // Generate keypair
    keys = sjcl.ecc.ecdsa.generateKeys(256, 10);
    identity.publicKey = JSON.stringify(keys.pub.serialize());

    // Store private key
    localStorage['PrivateKey'] = JSON.stringify(keys.sec.serialize());

    // Expiration (1 year from now)
    millisInaYear = 365 * 24 * 60 * 60 * 1000;
    oneYearHence = Date.now() + millisInaYear;

    // Self sign the assured fields
    assuredFields = {"Identity": identity, "Expiration": oneYearHence};
    hash = sjcl.hash.sha256.hash(JSON.stringify(assuredFields));
    signatures = {};
    signatures[identity.publicKey] = keys.sec.sign(hash);

    // Store the certificate locally
    cert = {"AssuredFields": assuredFields, "Signatures": signatures};
    localStorage['Certificate'] = JSON.stringify(cert);

    // DEBUG
    alert(JSON.stringify(JSON.parse(localStorage['Certificate']), "", 2));

    // Add "Dash" to pageSelect if it doesn't already exist and show the Dash
    pageSelect = document.getElementById("PageSelect");
    dashIndex = -1;
    for (i in pageSelect.options)
    {
        if (pageSelect.options[i].value == "Dash")
        {
            dashIndex = i;
            break;
        }
    }
    if (dashIndex == -1)
    {
        pageSelect.innerHTML += '<option value="Dash">Dash</option>';
        pageSelect.selectedIndex = pageSelect.length - 1;
    }
    else
    {
        pageSelect.selectedIndex = dashIndex;
    }
    showSection("Dash");
}
